import math
import turtle as t
def snow(start,end,n=1):
    if n==1:
        # 计算start点到end点的长度和角度
        length = pow((end[0]-start[0])**2+(end[1]-start[1])**2,0.5)
        angle = math.degrees(math.atan2(end[1]-start[1], end[0]-start[0]))
        t.penup()
        t.goto(start[0],start[1])
        t.pendown()
        t.seth(angle)
        t.fd(length/3)
        t.left(60)
        t.fd(length/3)
        t.right(120)
        t.fd(length/3)
        t.left(60)
        t.fd(length/3)
    else:
        x1 = (start[0]+(end[0]-start[0])/3,start[1]+(end[1]-start[1])/3)
        x2 = (start[0]+(end[0]-start[0])*2/3,start[1]+(end[1]-start[1])*2/3)
        # 计算等边三角形的第三个点
        dx = x2[0] - x1[0]
        dy = x2[1] - x1[1]
        x_middle = (
            x1[0] + dx/2 - dy*math.sqrt(3)/2,
            x1[1] + dy/2 + dx*math.sqrt(3)/2
        )
        snow(start,x1,n-1)
        snow(x1,x_middle,n-1)
        snow(x_middle,x2,n-1)
        snow(x2,end,n-1)
    

if __name__=='__main__':
    t.setup(800,800)
    t.speed(0)
    t.penup()
    t.goto(-100,-100)
    t.pendown()
    order = 3
    #初始化等边三角形的两个点
    x1 = t.pos()
    x2 = (x1[0]+300,x1[1])
    # 计算等边三角形的第三个点
    dx = x2[0] - x1[0]
    dy = x2[1] - x1[1]
    x_middle = (
        x1[0] + dx/2 - dy*math.sqrt(3)/2,
        x1[1] + dy/2 + dx*math.sqrt(3)/2
    )
    snow(x1,x_middle,order)
    snow(x_middle,x2,order)
    snow(x2,x1,order)
    
    
    t.hideturtle()
    t.done()
